import BaseModel from './BaseModel'
import { post, del, get } from '@/api/ajax'
import ArticleModel from './ArticleModel'
import Store from '@/store'
import { UserApi } from '@/api/apis'
import { UserType } from './types'

class AccountModel extends BaseModel{

  /**
   * 用户名
   */
  public name = ''
  /**
   * 用户类型
   */
  public type = UserType.SUPER_ADMIN
  public typeStr!: string
  // 账号登录错误次数
  public loginErrNum = 0
  // 项目数组
  public projects = []
  // 项目模型数组
  public articleModels: Array<ArticleModel> = []
  // 是否是当前账号
  public isCurrent = false
  // 是否启用
  public enabled = false
  // 加载列表的API
  static loadListApi = UserApi.crud
  // 删除数据的API
  removeDataApi = UserApi.crud
  // 添加数据的API
  addModelApi = UserApi.crud
  // 添加项目的字段
  addModelField = 'name pass type code'
  // 当前的项目
  currentProject?: ArticleModel
  // 验证码(添加的时候使用)
  code = ''
  // 密码(添加的时候使用)
  pass = ''

  get isSuperAdmin() {
    return this.type === UserType.SUPER_ADMIN
  }

  setDataWithJson(json: {}) {
    super.setDataWithJson(json);
    this.typeStr = this.type === UserType.SUPER_ADMIN ? '超级管理员' : '管理员'
    this.isCurrent = this.name === Store.getters.userName
    this.enabled = this.enabled && this.loginErrNum < 2
    this.articleModels = ArticleModel.getModelsWithArr(this.projects)
  }

  /**
   * 账号是否可用
   */
  accountEnabled() {
    return post(UserApi.updateEnabled, {
      id: this._id,
      enabled: this.enabled
    })
  }

  /**
   * 修改密码（修改其他人的密码）
   */
  changePassword(query: any) {
    return post(UserApi.updateUserPass, {
      id: this._id,
      ...query
    })
  }

  /**
   * 添加项目
   */
  addProject(projectId: string) {
    return post(`${UserApi.addProject}/${this._id}`, {
      projectId
    })
  }
  /**
   * 删除项目
   */
  removeProject(projectId: string) {
    return del(`${UserApi.removeProject}/${this._id}`, {
      projectId
    })
  }
  /**
   * 获取当前账户下的项目列表
   */
  static projectList(): Promise<Array<ArticleModel>> {
    return new Promise<Array<ArticleModel>>((resolve, reject) => {
      get<Array<ArticleModel>>(UserApi.projectList).then((dataArr: Array<ArticleModel>) => {
        resolve(ArticleModel.getModelsWithArr(dataArr))
      }).catch(() => {
        reject()
      })
    })
  }
}

export default AccountModel
